package com.yww.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yww.entity.*;
import com.yww.mapper.StudentMapper;
import com.yww.service.IAutoService;
import com.yww.service.IStudentService;
import com.yww.service.UsersService;
import com.yww.utils.PoiUtils;
import com.yww.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 雯雯yang
 * @since 2020-06-02
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    IStudentService iStudentService;
    @Autowired
    UsersService usersService;
    @Autowired
    IAutoService service;
    @Autowired
    StudentMapper studentMapper;

    /**
     * (查) 多条件分页查询学生plus
     *
     * @param student
     * @return
     */
    @RequestMapping("/getStuListp")
    public Object getStuListp(StuParam student, @RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false, defaultValue = "10") Integer limit) {
        //分页-需要分页的配置文件
        Page<Student> p = new Page<>(page, limit);
        //多条件
        QueryWrapper<Student> queryWrapper = new QueryWrapper<Student>();
        if (!StringUtils.isEmpty(student.getStuName())) {
            queryWrapper.like("stu_name", student.getStuName());
        }
        if (!StringUtils.isEmpty(student.getStuPhone())) {
            queryWrapper.like("stu_phone", student.getStuPhone());
        }
        if (!StringUtils.isEmpty(student.getUsersId())) {
            queryWrapper.eq("users_id", student.getUsersId());
        }
        if (!StringUtils.isEmpty(student.getIsPay())) {
            queryWrapper.eq("is_pay", student.getIsPay());
        }
        if (!StringUtils.isEmpty(student.getIsYx())) {
            queryWrapper.eq("is_yx", student.getIsYx());
        }
        if (!StringUtils.isEmpty(student.getIsHf())) {
            queryWrapper.eq("is_hf", student.getIsHf());
        }
        if (!StringUtils.isEmpty(student.getStuQq())) {
            queryWrapper.eq("stu_qq", student.getStuQq());
        }
        if (!StringUtils.isEmpty(student.getStuAddress())) {
            queryWrapper.like("stu_address", student.getStuAddress());
        }
        if (!StringUtils.isEmpty(student.getStartTime())) {
            queryWrapper.gt("create_time", student.getStartTime());
        }
        if (!StringUtils.isEmpty(student.getEndTime())) {
            queryWrapper.lt("create_time", student.getEndTime());
        }
        if (!StringUtils.isEmpty(student.getBeforeTime())) {
            queryWrapper.gt("sm_time", student.getBeforeTime());
        }
        if (!StringUtils.isEmpty(student.getAfterTime())) {
            queryWrapper.lt("sm_time", student.getAfterTime());
        }


        //查询方法
        Page<Student> ipage = iStudentService.page(p, queryWrapper);
        //获取数据和总条数
        List<Student> data = ipage.getRecords();
        long total = ipage.getTotal();
        return new Result(0, "", total, data);
    }


    /**
     * (查) 多条件分页查询学生mybatis
     *
     * @param stuParam
     * @return
     */
    @RequestMapping("/getStuList")
    public Object getStuList(StuParam stuParam) {
        System.out.println("开始查询");
        List<StuParam> student = iStudentService.getStuList(stuParam);
        stuParam.setLimit(null);
        stuParam.setPage(null);
        List<StuParam> con1 = iStudentService.getStuList(stuParam);
        if (student != null) {
            return new Result(0, "查询成功", con1.size(), student);
        } else {
            return new Result(1, "查询失败");
        }

    }


    /**
     * 添加学生时
     * 了解是否自动分配给用户
     * @param student
     * @return
     */
    /**
     * 添加时判断是否自动分配给用户
     * <p>
     * 拿到权重最大待分配用户
     * 如果存在添加用户，并且添加成功时修改用户的分配状态为已分配
     * 如果不存在让所有的用户的分配状态全部改为待分配
     * 0:
     * 1：已分配
     *
     * @param s
     * @return
     */

    @RequestMapping("/addStu")
    public Object add(@Valid Student s) {
        Auto byId = service.getOne(new QueryWrapper<Auto>().eq("auto_id", 1));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        // 判断是否开启自动分配0：开启1：关闭
        if (byId.getYesNo() == 0) {

            List<Users> getzixunshi1 = usersService.getCon(null);
            // 获取集合中的属性添加到数组中
            List<Integer> str1 = new ArrayList<Integer>();
            List<Integer> str = new ArrayList<Integer>();
            System.out.println("bb");
            for (int i = 0; i < getzixunshi1.size(); i++) {
                str1.add(i, getzixunshi1.get(i).getQdStatic());
                if (getzixunshi1.get(i).getQdStatic() == 1) {
                    str.add(i, getzixunshi1.get(i).getUserId());
                } else {
                    str.add(i, 0);
                }
            }
            //判断咨询师存在已打卡
            if (str1.contains(1)) {
                //查询待分配的
                // 咨询师
                Users one2 = usersService.getOne(new QueryWrapper<Users>().eq("is_fp", 1).orderByDesc("weight").last("limit 0 , 1"));
                //如果没查到待分配，
                if (one2 == null) {
                    usersService.updateOpenButton(str, 1);
                    //此时咨询师全部为待分配进行行查询
                    Users one3 = usersService.getOne(new QueryWrapper<Users>().eq("is_fp", 1).orderByDesc("weight").last("limit 0 , 1"));
                    Integer userId3 = one3.getUserId();
                    s.setUsersId(userId3);
                    Date date = new Date();
                    s.setFpTime(date);
                    s.setIsFenpei("是");
                    s.setCreateTime(sdf.format(d));
                    //添加学生时给学生添加咨询师
                    boolean save = iStudentService.save(s);
                    if (save) {
                        Users u = new Users();
                        u.setIsFp(0);
                        usersService.update(u, new QueryWrapper<Users>().eq("user_id", userId3));
                        return new Result(0, "添加成功");
                    }
                    return new Result(1, "添加失败");
                } else {
                    Integer userId = one2.getUserId();
                    s.setUsersId(userId);
                    s.setCreateTime(sdf.format(d));
                    boolean save = iStudentService.save(s);
                    if (save) {
                        Users u = new Users();
                        u.setIsFp(0);
                        s.setIsFenpei("否");
                        //修改咨询师状态为已分配
                        usersService.update(u, new QueryWrapper<Users>().eq("user_id", userId));
                        return new Result(0, "添加成功");
                    }
                    return new Result(1, "添加失败");
                }
            } else {
                s.setCreateTime(sdf.format(d));
                s.setIsFenpei("否");
                boolean save = iStudentService.save(s);
                if (save) {
                    return new Result(0, "添加成功");
                }
                return new Result(1, "添加失败");
                //未获取到已打卡的咨询师
            }
        } else {
            s.setCreateTime(sdf.format(d));
            s.setIsFenpei("否");
            boolean save = iStudentService.save(s);
            if (save) {
                return new Result(0, "添加成功");
            }
            return new Result(1, "添加失败");
        }

    }


    /**
     * 删除学生
     *
     * @param student
     * @return
     */
    @RequestMapping("/delStu")
    public Object delStu(Student student) {
        student.setIsDelete(1);
        student.setDelTime(new Date());
        boolean b = iStudentService.updateById(student);
        if (b) {
            return new Result(0, "删除成功");
        }
        return new Result(1, "删除失败");
    }


    @RequestMapping("/updStu")
    public Object updStu(Student student) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(student.getIsPay()!=null && student.getIsPay()==0){
            Date date = new Date();
            student.setPayTime(sdf.format(date));
        }
        boolean save = iStudentService.updateById(student);
        if (save) {
            return new Result(0, "修改成功");
        }
        return new Result(1, "修改失败");
    }


    /**
     * 学生批量导出
     *
     * @param ids
     * @param response
     * @throws IOException
     */
    @RequestMapping("/exportStudent")
    public void exportStudent(String ids, HttpServletResponse response) throws IOException {
        System.out.println(ids);
        //分割数组
        String[] id = ids.split(",");
        //设置下载Excel文档名
        String downloadName = "导出的学生的文件.xlxs";
        //设置字符集编码
        response.setCharacterEncoding("UTF-8");
        //响应文件格式为excel类型
        response.setContentType("application/vnd.ms-excel");
        //文件下载处理
        response.setHeader("Content-disposition", "attachment;filename" + new String(downloadName.getBytes("GB2312"), "ISO-8859-1"));
        ServletOutputStream outputStream = response.getOutputStream();
        List<Student> stu = null;
        if (ids != null && !ids.equals("")) {
            stu = iStudentService.exportStudent(id);

        }
        PoiUtils p = new PoiUtils();
        p.createExcel(stu, Student.class, outputStream);

    }

    /**
     * 学生批量导入
     *
     * @param file
     * @return
     */
    @RequestMapping("/uploadStu")
    public Object uploadStudents(@RequestParam("file") MultipartFile file) {
        String name = file.getName();//form表单中参数名称
        String originalFileName = file.getOriginalFilename();//得到上传文件的名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PoiUtils poiUtils = new PoiUtils();//Excel工具类
        List<Student> list = null;
        List<Student> l = new ArrayList<Student>();
        try {
            list = (List<Student>) poiUtils.parseExcel(Student.class, file.getInputStream(), originalFileName);
            for (Student students : list) {
                l.add(students);
            }
            boolean b = iStudentService.saveBatch(l);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (l != null) {
            return new Result(0, "上传成功", true);
        } else {
            return new Result(1, "上传失败", false);
        }
    }


    /**
     * 查看分配给咨询师的学生信息
     *
     * @param usersParam
     * @param stuParam
     * @return
     */
    @RequestMapping("/selectStuListByCon")
    public Object selectStuListByCon(UsersParam usersParam, StuParam stuParam, Integer userId) {
        usersParam.setUserId(userId);
        List<StuParam> stuParams = iStudentService.selectStuListByCon(stuParam);
        stuParam.setPage(null);
        stuParam.setLimit(null);
        List<StuParam> stuParams1 = iStudentService.selectStuListByCon(stuParam);
        if (stuParams != null) {
            return new Result(0, "查询成功", stuParams1.size(), stuParams);
        }
        return new Result(0, "查询失败");
    }


    /**
     * 查看分配给网络咨询师的学生信息
     *
     * @param stuParam
     * @return
     */
    @RequestMapping("/selectStuListByWWWCon")
    public Object selectStuListByWWWCon(StuParam stuParam) {
        List<StuParam> stuParams = iStudentService.selectStuListByWWWCon(stuParam);
        stuParam.setPage(null);
        stuParam.setLimit(null);
        List<StuParam> stuParams1 = iStudentService.selectStuListByWWWCon(stuParam);
        if (stuParams != null) {
            return new Result(0, "查询成功", stuParams1.size(), stuParams);
        }
        return new Result(0, "查询失败");
    }


    /**
     * 一键分配
     *
     * @return
     */
    @RequestMapping("/setOnceAuto")
    public Object setOnceAuto() {
        //查询签到用户
        QueryWrapper<Users> userquery = new QueryWrapper<Users>();
        userquery.eq("qd_static", 1);//已经签到
        //获取咨询师
        List<Users> getzixunshi1 = usersService.getCon(null);
        List<Integer> str = new ArrayList<Integer>();
        for (int i = 0; i < getzixunshi1.size(); i++) {
            if (getzixunshi1.get(i).getQdStatic() == 1) {//已经签到
                str.add(i, getzixunshi1.get(i).getUserId());
            } else {
                str.add(0);
            }

        }
        userquery.in("user_id", str);
        //获取已签到咨询师
        List<Users> list = usersService.list(userquery);
        //不存在已签到咨询师
        if (list.size() != 0) {
            //查询待分配，权重倒叙排列
            userquery.eq("is_fp", 0);//待分配
            userquery.orderByDesc("weight");
            userquery.last("limit 0 , 1");

            System.out.println(list);
            //获取咨询师为空的学生
            QueryWrapper<Student> stuquery = new QueryWrapper<Student>();
            stuquery.isNull("users_id");
            List<Student> list2 = iStudentService.list(stuquery);
            System.out.println(list2);
            List<Users> userlist = null;
            int count = 0;
            //遍历学生
            for (Student s : list2) {
                //获取待分配权重最大的用户
                userlist = usersService.list(userquery);
                System.out.println(userlist);
                //如果不存在已签到未分配的咨询师，设置所有签到咨询师为待分配
                if (userlist.size() == 0) {
                    usersService.updateOpenButton(str, 0);//未分配
                    //获取待分配权重最大的用户
                    userlist = usersService.list(userquery);

                }
                //给此用户分配权重最大的的咨询师
                Users uu = userlist.get(0);
                s.setUsersId(uu.getUserId());
                uu.setIsFp(1);//已分配
                s.setIsFenpei("是");
                s.setFpTime(new Date());
                System.out.println(uu);
                //分配时间
//                Date date = new Date();
//                s.setFpTime(date);
                //分配时间
                usersService.update(uu, new QueryWrapper<Users>().eq("user_id", uu.getUserId()));
                boolean update = iStudentService.update(s, new QueryWrapper<Student>().eq("stu_id", s.getStuId()));
                if (update) {
                    count = count + 1;
                } else {
                    count = 0;
                }

            }
            System.out.println(count);
            System.out.println(list2.size());
            //批量设置学生咨询师
            if (count == list2.size()) {
                return new Result(0, "设置成功");
            } else {
                return new Result(1, "设置失败");
            }
            /*
             * boolean updateBatchById = studentService.updateBatchById(list2);
             * if(updateBatchById) { return new Result(0, "设置成功"); }else { return new
             * Result(1, "设置失败"); }
             */
        } else {
            return new Result(1, "设置失败，所有咨询师未签到");
        }

    }


    @RequestMapping("/delBatchId")
    public Object delBatchId(String ids) {
        String[] id = ids.split(",");
        Integer i = iStudentService.delBatchId(id);
        if(i>0){
            return new Result(0,"删除成功");
        }
        return new Result(1,"删除失败");
    }


    /**
     * 批量分配
     * @param ids
     * @return
     */
    @RequestMapping("/updBatchId")
    public Object updBatchId(String ids,Integer usersId,Student s) {
        System.out.println("test");
        String[] id = ids.split(",");
        Date date = new Date();
        s.setFpTime(date);

        Integer i = iStudentService.updBatchId(id,usersId);
        if(i>0){
            return new Result(0,"分配成功");
        }
        return new Result(1,"分配失败");
    }



    @RequestMapping("/getStuListDelete")
    public Object getStuListDelete(StuParam stuParam){
        List<StuParam> stuParams = iStudentService.getStuListDelete(stuParam);
        stuParam.setPage(null);
        stuParam.setLimit(null);
        List<StuParam> stuParams1 = iStudentService.getStuListDelete(stuParam);
        if (stuParams != null) {
            return new Result(0, "success", stuParams1.size(), stuParams);
        }
        return new Result(0, "fail");
    }

    @RequestMapping("/updIsDelete")
    public Object updIsDelete(Student student) {
        student.setIsDelete(0);
        boolean b = iStudentService.updateById(student);
        if(b){
            return new Result(0,"恢复成功");
        }
        return new Result(1,"恢复失败");
    }


    /**
     * (查) 多条件分页查询已缴费学生plus
     *
     * @param stuParam
     * @return
     */
    @RequestMapping("/getStuListByIsPay")
    public Object getStuListByIsPay(StuParam stuParam, @RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false, defaultValue = "10") Integer limit) {
        List<StuParam> stuParams = iStudentService.getStuListByIsPay(stuParam);
        stuParam.setPage(null);
        stuParam.setLimit(null);
        List<StuParam> stuParams1 = iStudentService.getStuListByIsPay(stuParam);
        if (stuParams != null) {
            return new Result(0, "success", stuParams1.size(), stuParams);
        }
        return new Result(0, "fail");
    }



    @RequestMapping("/updateJoinStatus")
    public Object updateJoinStatus(Student student){
        student.setIsJoin(0);
        boolean b = iStudentService.updateById(student);
        if(b){
            return new Result(0,"已进班");
        }
        return new Result(1,"因为特殊情况 未进班...");
    }

    /**
     * 批量分配进班
     * @param ids
     * @param id
     * @return
     */
    @RequestMapping("/autoUserClass")
    public Object autoUserClass(String ids, Integer id) {
        System.out.println(id);
        System.out.println(ids);
        boolean updateBatch = iStudentService.updateBatchClass(id, ids);
        if (updateBatch) {
            return new Result(0, "成功进班");
        }
        return new Result(1, "进班失败");
    }


    /**
     * 关注客户过程
     * @param sid
     * @param num
     * @return
     */
    @RequestMapping("/stuConcern")
    public Object stuConcern(Integer sid,Integer num) {
       Student student=new Student();
       student.setStuId(sid);
       student.setStuConcern(num);
        boolean update = studentMapper.updateStuConcern(num,sid);
        if(num==1) {
            if (update) {
                return new Result(0, "取关成功");
            }
            return new Result(1, "取关失败");
        }else {
            if (update) {
                return new Result(0, "关注成功");
            }
            return new Result(1, "关注失败");
        }

    }


}
